import {
  NAV_MENU_KEY,
  ROLE_MENU_KEY,
  TOKEN_SESSION_KEY,
  USER_PERMISSIONS,
} from "@/config/tokenConstant";
import { LoginUserInfoVO } from "@/pojo/LoginUserInfoVO";
import { Module } from "vuex";
import { RootState, UserState } from "../../types";

const userModule: Module<UserState, RootState> = {
  namespaced: true,
  state: {
    username: "",
    roleName: "",
    roleId: "",
    userToken: "",
    navMenus: [],
    roleMenus: [],
    permissions: [],
  },
  getters: {},
  actions: {},
  mutations: {
    /***
     * 退出登录
     */
    logout(state) {
      state.userToken = "";
      state.username = "";
      state.roleName = "";
      state.roleId = "";
      state.navMenus = [];
      state.roleMenus = [];
      state.permissions = [];
      window.localStorage.removeItem(TOKEN_SESSION_KEY);
      window.localStorage.removeItem(USER_PERMISSIONS);
      window.localStorage.removeItem(NAV_MENU_KEY);
      window.localStorage.removeItem(ROLE_MENU_KEY);
    },
    /***
     * 存储用户登录TOKEN
     */
    setUserToken(state, payload: string) {
      state.userToken = payload;
      window.localStorage.setItem(TOKEN_SESSION_KEY, payload);
    },
    /***
     * 存储用户登录信息
     */
    setLoginUserInfo(state, payload: LoginUserInfoVO) {
      state.username = payload.username;
      state.roleName = payload.roleName;
      state.roleId = payload.roleId;
      state.navMenus = payload.navMenus;
      state.roleMenus = payload.roleMenus;
      state.permissions = payload.permissions;

      // 缓存侧栏菜单和权限菜单
      window.localStorage.setItem(
        USER_PERMISSIONS,
        JSON.stringify(payload.permissions)
      );

      window.localStorage.setItem(
        NAV_MENU_KEY,
        JSON.stringify(payload.navMenus)
      );

      window.localStorage.setItem(
        ROLE_MENU_KEY,
        JSON.stringify(payload.roleMenus)
      );
    },
  },
};

export default userModule;
